package com.yl.chainStore.services.impl.warehouse

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper
import com.yl.chainStore.common.LockObjects
import com.yl.chainStore.common.enums.Status
import com.yl.chainStore.common.enums.TypeEnum
import com.yl.chainStore.entity.warehouse.WarehouseDispatchOrder
import com.yl.chainStore.entity.warehouse.WarehouseDispatchOrderDetail
import com.yl.chainStore.mapper.warehouse.WarehouseDispatchOrderDetailMapper
import com.yl.chainStore.mapper.warehouse.WarehouseDispatchOrderMapper
import com.yl.chainStore.pojo.vo.warehouse.OutBatchCountVo
import com.yl.chainStore.pojo.vo.warehouse.UpdateWarehouseGoodVo
import com.yl.chainStore.services.warehouse.IWarehouseDispatchOrderService
import com.yl.chainStore.services.warehouse.IWarehouseService
import com.yl.common.ErrorCode
import com.yl.common.control.ResponseBody
import com.yl.common.control.returnError
import com.yl.common.control.returnSuccess
import com.yl.common.getContext
import com.yl.users.services.ICompanyDeptService
import com.yl.users.services.ICompanyUserService
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
import java.util.*

@Service
class WarehouseDispatchOrderServiceImpl(
	private val warehouseDispatchOrderMapper: WarehouseDispatchOrderMapper,
	private val warehouseDispatchOrderDetailMapper: WarehouseDispatchOrderDetailMapper,
) : IWarehouseDispatchOrderService {

	companion object {
		private val log = LoggerFactory.getLogger(IWarehouseDispatchOrderService::class.java)
	}

	@Autowired
	lateinit var iWarehouseService: IWarehouseService

	@Autowired
	lateinit var iCompanyUserService: ICompanyUserService

	@Autowired
	lateinit var iCompanyDeptService: ICompanyDeptService

	override fun addDetail(detail: WarehouseDispatchOrderDetail): ResponseBody {
		warehouseDispatchOrderDetailMapper.insert(detail)
		return returnSuccess()
	}

	override fun dispatchOrder(id: Long): WarehouseDispatchOrder? {
		log.info("仓库订单管理：调度详情：id{}", id)
		val order = warehouseDispatchOrderMapper.selectById(id) ?: return null

		val inDept = iCompanyDeptService.getDept(order.inDeptId)
		if (inDept != null) {
			order.inName = inDept.name
		}


		val outDept = iCompanyDeptService.getDept(order.outDeptId)
		if (outDept != null) {
			order.outName = outDept.name
		}

		if (order.inUserId != null) {
			val user = iCompanyUserService.getUser(order.inUserId!!)
			if (user != null) {
				order.inUserName = user.realName
			}
		}
		if (order.outUserId != null) {
			val user = iCompanyUserService.getUser(order.outUserId!!)
			if (user != null) {
				order.outUserName = user.realName
			}
		}

		val user = iCompanyUserService.getUser(order.createUserId)
		if (user != null) {
			order.createUserName = user.realName
		}
		return order
	}

	override fun getOrderDetails(orderId: Long): List<WarehouseDispatchOrderDetail> {
		return warehouseDispatchOrderDetailMapper.selectListByOrderId(orderId)
	}

	private fun confirmDispatchOrderOut(orderId: Long): ResponseBody {
		log.info("仓库订单管理：调度单：出库确认：orderId{}", orderId)
		val warehouseDispatchOrder =
			warehouseDispatchOrderMapper.selectById(orderId) ?: return returnError(ErrorCode.DATA_IS_NOT_FIND, "未找到调度单")

		warehouseDispatchOrder.details = warehouseDispatchOrderDetailMapper.selectListByOrderId(orderId)
		return confirmDispatchOrderOut(warehouseDispatchOrder)
	}

	private fun confirmDispatchOrderOut(dispatchOrder: WarehouseDispatchOrder): ResponseBody {
		log.info("仓库订单管理：调度单：出库确认：dispatchOrder{}", dispatchOrder)
		if (dispatchOrder.outStatus != Status.WAIT_AUDIT) {
			return returnError(ErrorCode.OPERATION_DATA_ERROR, "订单已被处理")
		}
		dispatchOrder.outStatus = Status.COMPLETE

		val dealUserId = getContext().userId
		dispatchOrder.outUserId = dealUserId
		dispatchOrder.outDealTime = Date()
		warehouseDispatchOrderMapper.updateById(dispatchOrder)
		var i = 1
		if (!dispatchOrder.details.isNullOrEmpty()) {
			val str: String = dispatchOrder.companyId.toString() + "_" + dispatchOrder.outDeptId.toString()
			synchronized(LockObjects.getWarehouseLock(str)) {
				for (detail in dispatchOrder.details!!) {
					log.info("仓库订单管理：出库确认：详情确认：detail{}", detail)
					detail.outStatus = Status.COMPLETE

					val log = UpdateWarehouseGoodVo(
						associatedType = TypeEnum.WAREHOUSE_LOG_TYPE_DISPATCH_ORDER_OUT,
						associatedId = dispatchOrder.id,
						remark = detail.remark,
						deptId = dispatchOrder.outDeptId,
						companyId = dispatchOrder.companyId,
						itemId = detail.itemId,
						goodCount = detail.goodCount,
						detailId = detail.id
					)

					val outResponseBody = iWarehouseService.outWarehouse(detail.outWarehouseGoodBatchId, log)
					if (outResponseBody.code != ErrorCode.SUCCESS.code) {
						return returnError(ErrorCode.OPERATION_DATA_ERROR, "第" + i + "行物品出库失败:" + outResponseBody.msg)
					}
					val resList = outResponseBody.data as List<*>
					warehouseDispatchOrderDetailMapper.deleteById(detail.id)
					for(vo in resList){
						vo as OutBatchCountVo
						detail.id = 0
						detail.goodCount = vo.count
						detail.outWarehouseGoodBatchId = vo.id
						detail.goodPrice = vo.price
						warehouseDispatchOrderDetailMapper.insert(detail)
					}
					i++
				}
			}

		}
		return returnSuccess()
	}

	private fun confirmDispatchOrderIn(orderId: Long): ResponseBody {
		log.info("仓库订单管理：调度单：入库确认：orderId{}", orderId)
		val warehouseDispatchOrder =
			warehouseDispatchOrderMapper.selectById(orderId) ?: return returnError(ErrorCode.DATA_IS_NOT_FIND, "未找到调度单")

		warehouseDispatchOrder.details = warehouseDispatchOrderDetailMapper.selectListByOrderId(orderId)
		return confirmDispatchOrderIn(warehouseDispatchOrder)
	}

	private fun confirmDispatchOrderIn(dispatchOrder: WarehouseDispatchOrder): ResponseBody {
		//目前需要完整数据
		log.info("仓库订单管理：调度单：入库确认：inOrder{}", dispatchOrder)
		if (dispatchOrder.details.isNullOrEmpty()) {
			return returnError(ErrorCode.PARAM_EMPTY, "没有物品")
		}
		if (dispatchOrder.outStatus != Status.COMPLETE) {
			return returnError(ErrorCode.OPERATION_DATA_ERROR, "订单出库未完成")
		}
		if (dispatchOrder.inStatus != Status.WAIT_AUDIT) {
			return returnError(ErrorCode.OPERATION_DATA_ERROR, "订单已被处理")
		}
		dispatchOrder.inStatus = Status.COMPLETE
		dispatchOrder.inUserId = getContext().userId
		dispatchOrder.inDealTime = Date()
		warehouseDispatchOrderMapper.updateById(dispatchOrder)
		val str: String = dispatchOrder.companyId.toString() + "_" + dispatchOrder.inDeptId.toString()
		synchronized(LockObjects.getWarehouseLock(str)) {
			for (detail in dispatchOrder.details!!) {
				log.info("仓库订单管理：入库确认：明细确认（入库）：detail{}", detail)
				detail.inStatus = Status.COMPLETE
				//组装入库记录 然后入库
				val log = UpdateWarehouseGoodVo(
					associatedType = TypeEnum.WAREHOUSE_LOG_TYPE_DISPATCH_ORDER_IN,
					associatedId = dispatchOrder.id,
					remark = detail.remark,
					deptId = dispatchOrder.inDeptId,
					companyId = dispatchOrder.companyId,
					itemId = detail.itemId,
					goodCount = detail.goodCount,
					unitPrice = detail.goodPrice,
					detailId = detail.id
				)

				val inWarehouse = iWarehouseService.inWarehouse(null,log)
				if (inWarehouse.code != ErrorCode.SUCCESS.code) {
					return inWarehouse
				}
				warehouseDispatchOrderDetailMapper.updateById(detail)
			}
		}

		return returnSuccess()
	}

	override fun completeDispatchOrder(id: Long): ResponseBody {
		val confirmDispatchOrderOut = confirmDispatchOrderOut(id)
		if (confirmDispatchOrderOut.code != ErrorCode.SUCCESS.code) {
			return confirmDispatchOrderOut
		}
		return confirmDispatchOrderIn(id)
	}

	override fun noPassDispatchOrder(id: Long): ResponseBody {
		log.info("调度单管理：调度单审核不通过：id{}", id)
		val outOrder =
			warehouseDispatchOrderMapper.selectById(id) ?: return returnError(ErrorCode.DATA_IS_NOT_FIND, "未找到调度单")
		if (outOrder.inStatus != Status.WAIT_AUDIT || outOrder.outStatus != Status.WAIT_AUDIT) {
			return returnError(ErrorCode.OPERATION_DATA_ERROR, "订单已被处理")
		}
		val details =
			warehouseDispatchOrderDetailMapper.selectList(
				QueryWrapper<WarehouseDispatchOrderDetail?>().eq(
					"dispatch_order_id",
					id
				)
			)

		outOrder.inUserId = getContext().userId
		outOrder.outUserId = getContext().userId
		outOrder.inStatus = Status.NO_PASS
		outOrder.outStatus = Status.NO_PASS
		if (!details.isNullOrEmpty()) {
			for (detail in details) {
				detail.inStatus = Status.NO_PASS
				detail.outStatus = Status.NO_PASS
				warehouseDispatchOrderDetailMapper.updateById(detail)
			}
		}
		warehouseDispatchOrderMapper.updateById(outOrder)
		return returnSuccess()
	}

	override fun cancelDispatchOrder(id: Long): ResponseBody {
		log.info("仓库订单管理：取消出库：id{}", id)
		val outOrder =
			warehouseDispatchOrderMapper.selectById(id) ?: return returnError(ErrorCode.DATA_IS_NOT_FIND, "未找到调度单")
		if (outOrder.inStatus != Status.WAIT_AUDIT || outOrder.outStatus != Status.WAIT_AUDIT) {
			return returnError(ErrorCode.OPERATION_DATA_ERROR, "订单已被处理")
		}
		val details =
			warehouseDispatchOrderDetailMapper.selectList(
				QueryWrapper<WarehouseDispatchOrderDetail?>().eq(
					"dispatch_order_id",
					id
				)
			)

		outOrder.inUserId = getContext().userId
		outOrder.outUserId = getContext().userId
		outOrder.inStatus = Status.SCRAP
		outOrder.outStatus = Status.SCRAP
		if (!details.isNullOrEmpty()) {
			for (detail in details) {
				detail.inStatus = Status.SCRAP
				detail.outStatus = Status.SCRAP
				warehouseDispatchOrderDetailMapper.updateById(detail)
			}
		}
		warehouseDispatchOrderMapper.updateById(outOrder)
		return returnSuccess()
	}

	override fun deleteDispatchOrder(id: Long): ResponseBody {
		log.info("调度单 ==>调度单删除：id{}", id)
		val order = warehouseDispatchOrderMapper.selectById(id)?: return returnSuccess()
		if(order.inStatus.code > Status.WAIT_AUDIT.code || order.outStatus.code > Status.WAIT_AUDIT.code){
			return returnError(ErrorCode.DATA_DELETE_FAILED,"订单已被处理")
		}
		warehouseDispatchOrderMapper.deleteById(id)
		return returnSuccess()
	}
}
